﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.Odbc;

namespace RookieLibSharp.Database
{
    public class DbAccess:IDatabase
    {
        private const string CONNECT_STR_PREFIX = "Provider=Microsoft.ACE.OLEDB.12.0 ;Data Source=";
        public string DatabaseFilePath{get;set;}
        private OleDbConnection connection;
        public DbAccess(string dbFilePath)
        {
            DatabaseFilePath = dbFilePath;
            string connectionStr = CONNECT_STR_PREFIX + this.DatabaseFilePath;
            connection = new OleDbConnection(connectionStr);
            connection.Open();
        }
        public void CloseDatabase()
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
            connection = null;
        }
        
        public DataTable GetAllData(string tableName)
        {
            DataTable dtRet = new DataTable();
            string connectionStr = CONNECT_STR_PREFIX + this.DatabaseFilePath;
            string cmdStr = "select * from " + tableName;
            try
            {
                OleDbDataReader reader = new OleDbCommand(cmdStr, connection).ExecuteReader();
                dtRet.Load(reader);
            }
            catch
            {

            }

            return dtRet;
        }
        public DataTable ExecuteReader(string command)
        {
            DataTable dtRet = new DataTable();
            try
            {
                OleDbDataReader reader = new OleDbCommand(command, connection).ExecuteReader();
                dtRet.Load(reader);
            }
            catch
            {

            }
            return dtRet;
        }
        public int ExecuteNonQuery(string queryString)
        {

            OleDbCommand command = new OleDbCommand(queryString, connection);
            try
            {
                int Ret = command.ExecuteNonQuery();
                return Ret;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }

        }
    }
}
